package org.ajax.test;

import com.google.gson.Gson;
import org.ajax.entity.User;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author CSY
 * @date 2024-11-19
 */
public class GsonTest01 {

    /**
     * 序列化：把Java对象转换为JSON字符串
     */
    public static void testToJson() {
        //实例化实体对象，封装相关的数据
        User user = new User("张三",28);
        //实例化Gson对象
        Gson gson = new Gson();
        //将实体对象转换为json字符串
        String json = gson.toJson(user);
    }

    /**
     * 反序列化：把JSON字符串转换为Java对象
     */
    public static void testFromJson() {
        //定义JSON字符串
        String json = "{\"username\":\"zs\",\"age\":18}";
        //实例化Gson对象
        Gson gson = new Gson();
        //将json字符串转换为实体对象
        //Gson对象.fromJson("json字符串",类名.class)
        User user = gson.fromJson(json, User.class);
        System.out.println(user.getUserName());
    }

    /**
     * 把List集合转换为JSON字符串
     */
    public static void testToJsonArray() {
        //实例化实体对象，封装相关的数据
        List<User> list = new ArrayList<>();
        User u1 = new User("张三",28);
        User u2 = new User("李四",20);
        User u3 = new User("王五",25);

        list.add(u1);
        list.add(u2);
        list.add(u3);
        //实例化Gson对象
        Gson gson = new Gson();
        //将实体对象转换为json字符串
        String json = gson.toJson(list);
        System.out.println(json);
    }

    /**
     * 把Map集合转换为JSON字符串
     */
    public static void testToJsonMap() {
        //实例化实体对象，封装相关的数据
        Map<String,User> map = new HashMap<>();
        User u1 = new User("张三",28);
        User u2 = new User("李四",20);
        User u3 = new User("王五",25);

        map.put("u1", u1);
        map.put("u2", u2);
        map.put("u3", u3);

        //实例化Gson对象
        Gson gson = new Gson();
        //将实体对象转换为json字符串
        String json = gson.toJson(map);
        System.out.println(json);
    }

    public static void main(String[] args) {
        testToJsonMap();
    }
}
